<template>
	<view class="wrap">
		<!-- 状态栏占位 -->
		<view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
		<!-- 搜索栏 -->
		<view class="search-bar" :style="{ width: statusBarWidth + 'px',height: menuHeight + 'px'}">
			<view class="dir">
				<text class="dir-text">目录</text>
				<u-icon name="arrow-down-fill" size="16" color="#666"></u-icon>
			</view>
			<view class="search-container">
				<u-search placeholder="搜索书架绘本" v-model="keyword" :show-action="false" shape="round" bg-color="#f5f5f5"></u-search>
			</view>
		</view>

		<!-- Tab栏 -->
		<u-tabs :list="tabs" :is-scroll="false" :current="currentTab" @change="onTabChange"></u-tabs>

		<!-- 内容区域 -->
		<view class="content">
			<!-- 阅读计划 -->
			<view class="plan-section">
				<view class="plan-header">
					<text class="title">阅读计划</text>
					<view class="plan-actions">
						<text class="view-all" @click="goToPlanList">查看全部</text>
						<text class="create-plan" @click="goToCreatePlan">+ 创建计划</text>
					</view>
				</view>
				<!-- 阅读计划列表 -->
				<view class="plan-list" v-if="planList.length > 0">
					<view class="plan-item" v-for="(plan, index) in planList.slice(0, 5)" :key="plan.id" @click="goToPlanDetail(plan.id)">
						<view class="plan-content">
							<view class="plan-header-info">
								<view class="plan-name">{{ plan.name  }}</view>
								<view class="plan-type">{{ plan.planType === 1 ? '绘本集计划' : '自定义计划' }}</view>
							</view>
							<view class="plan-progress">
								<text class="progress-text">第{{ plan.currentDay || 1 }}天 / 共{{ plan.plannedDays || 0 }}天</text>
							</view>
						</view>
						<view class="plan-arrow">
							<u-icon name="arrow-right" size="16" color="#999"></u-icon>
						</view>
					</view>
				</view>
				<!-- 空状态 -->
				<view class="plan-empty" v-else>
					<text class="empty-text">暂无阅读计划</text>
				</view>
			</view>

			<!-- 最近阅读 -->
			<view class="category-section">
				<view class="category-header">
					<text class="title">最近阅读</text>
					<u-icon name="arrow-right" color="#999"></u-icon>
				</view>
				<u-grid :col="3" :border="false">
					<u-grid-item v-for="(item, index) in recentlyRead" :key="index" @click="goToBookDetail(item)">
						<view class="book-card">
							<view class="book-cover" :style="{ backgroundImage: `url(${item.cover})` }">
                <view class="book-count">{{ item.bookCount }}本</view>
								<view class="recycle-icon" @click.stop="moveToRecycleBin(item)" v-if="item.id">
									<u-icon name="trash" size="16" color="#333"></u-icon>
								</view>
							</view>
							<text class="book-title">{{ item.title }}</text>
							<view class="book-meta">
								<text>来自: {{ item.author }}</text>
								<u-icon name="more-dot-fill" color="#ccc"></u-icon>
							</view>
						</view>
					</u-grid-item>
				</u-grid>
			</view>

			<!-- 牛津树系列 -->
			<view class="category-section">
				<view class="category-header">
					<text class="title">推荐绘本集</text>
					<u-icon name="arrow-right" color="#999"></u-icon>
				</view>
				<u-grid :col="3" :border="false">
					<u-grid-item v-for="(item, index) in oxfordTree" :key="index" @click="goToBookDetail(item)">
						<view class="book-card">
							<view class="book-cover" :style="{ backgroundImage: `url(${item.cover})` }">
								<view class="book-count">{{ item.bookCount }}本</view>
								<view class="recycle-icon" @click.stop="moveToRecycleBin(item)" v-if="item.id">
									<u-icon name="trash" size="16" color="#333"></u-icon>
								</view>
							</view>
							<text class="book-title">{{ item.title }}</text>
							<view class="book-meta">
								<text>来自: {{ item.author }}</text>
								<u-icon name="more-dot-fill" color="#ccc"></u-icon>
							</view>
						</view>
					</u-grid-item>
				</u-grid>
			</view>
		</view>
	</view>
</template>

<script>
	import * as BookShelfApi from '@/api/bookShelf'
	import * as BookRecordApi from '@/api/bookRecord'
	import * as BookApi from '@/api/book'

	export default {
		data() {
			return {
				statusBarHeight: 0,
        statusBarWidth: 0,
        menuHeight: 0,
				keyword: '',
				tabs: [{ name: '全部' }], // 默认显示全部，其他分类通过接口获取
				currentTab: 0,
				planList: [], // 阅读计划列表
				recentlyRead: [],
				oxfordTree: [] // 动态从接口获取数据
			};
		},
		async onLoad() {
			// 获取状态栏高度
			const systemInfo = uni.getSystemInfoSync();
			this.statusBarHeight = systemInfo.statusBarHeight || 0;
      this.statusBarWidth = systemInfo.windowWidth -  uni.getMenuButtonBoundingClientRect().width
      this.menuHeight = uni.getMenuButtonBoundingClientRect().height
			// 检查登录状态
			if (this.checkLoginStatus()) {
				// 获取阅读计划列表
				await this.loadPlanList();
				// 获取英文书架分类数据
				await this.loadCategoryData();
				// 获取绘本数据
				await this.loadBookData('1');
				// 获取最近阅读记录
				await this.loadRecentlyRead();
			}
		},
    onShow() {
      // 每次页面显示时重新获取数据
      this.loadPlanList();
	  this.loadRecentlyRead();
    },
    methods: {
			// 检查登录状态
			checkLoginStatus() {
				const token = this.$store.getters.token;
				if (!token) {
					// 没有token，跳转到登录页面
					uni.showModal({
						title: '提示',
						content: '请先登录后再使用此功能',
						confirmText: '去登录',
						cancelText: '取消',
						success: (res) => {
							if (res.confirm) {
								uni.reLaunch({
									url: '/pages/login/index'
								});
							}
						}
					});
					return false;
				}
				return true;
			},
			// 加载分类数据
			async loadCategoryData() {
				try {
					// 调用接口获取英文书架分类数据，type=1表示英文书架
					const response = await BookShelfApi.getCategoryListByType('1');
					if (response.code === 200 && response.data) {
						// 将接口返回的分类数据转换为tabs格式
						const categoryTabs = response.data.map(item => ({
							name: item.catalogueName || item.categoryName,
							id: item.id
						}));
						// 保留"全部"选项，并添加从接口获取的分类
						this.tabs = [{ name: '全部' }, ...categoryTabs];
					} else if (response.code === 0 && response.data) {
						// 处理 code 为 0 的情况
						const categoryTabs = response.data.map(item => ({
							name: item.catalogueName || item.categoryName,
							id: item.id
						}));
						this.tabs = [{ name: '全部' }, ...categoryTabs];
					}
				} catch (error) {
					console.error('获取分类数据失败:', error);
				}
			},
			async onTabChange(index) {
				this.currentTab = index;
				console.log('当前选中的tab索引:', index);

				// 根据选中的分类重新加载绘本数据
				if (index === 0) {
					// 选择"全部"时，加载所有绘本
					await this.loadBookData('1');
				} else {
					// 选择特定分类时，根据分类名称过滤绘本
					const selectedCategory = this.tabs[index];
					if (selectedCategory && selectedCategory.name) {
            console.log(selectedCategory.name);
						await this.loadBookData('1',selectedCategory.id);
					}
				}
			},
			goToCreatePlan() {
				uni.navigateTo({
					url: '/pages/plan/create?type=1'
				});
			},
			goToPlanList() {
				uni.navigateTo({
					url: '/pages/plan/index?type=1'
				});
			},
			// 获取阅读计划列表
			async loadPlanList() {
				try {
					const response = await BookRecordApi.getBookReadingProgramList('1');
					if (response.code === 0 && response.data) {
						this.planList = response.data.map(plan => ({
							...plan,
							currentDay: 1 // 这里可以根据实际业务逻辑计算当前天数
						}))
						.slice(0, 2); // 只保留前三条数据
					}
				} catch (error) {
					console.error('获取阅读计划列表失败:', error);
				}
			},
			// 跳转到计划详情
			goToPlanDetail(planId) {
				uni.navigateTo({
					url: '/pages/plan/detail?id=' + planId
				});
			},
			async goToBookDetail(item) {
        console.log("******");
				// 如果是最近阅读的书籍（有bookName属性），需要先获取书籍详情再跳转到图片轮播页面
				if (item.bookName) {
					try {
						// 先获取书籍详情，获取图片列表
						const bookResponse = await BookApi.getBookList({
							pageNo: '1',
							pageSize: '100',
							bookShelfId: item.id // 使用bookId作为bookShelfId查询
						});
            console.log("******0");

						let imageUrls = [];
						if ((bookResponse.code === 200 || bookResponse.code === 0) && bookResponse.data && bookResponse.data.list && bookResponse.data.list.length > 0) {
              console.log("******1");
							// 获取书籍的图片URL列表，并处理路径
							imageUrls = bookResponse.data.list.map(book => {
								if (book.cover && book.cover.trim() !== '') {
									// 如果接口返回了图片名称，拼接到静态资源路径前
									let imageName = book.cover;
									// 处理可能包含错误前缀的图片名称
									if (imageName.includes('__pageframe__/pages/video/')) {
										// 提取真正的图片名称
										imageName = imageName.replace(/.*__pageframe__\/pages\/video\//, '');
									}
									return `/static/url/${imageName}`;
								} else {
									// 如果url为空，使用默认图片
									return '/static/url/defualt_1.png';
								}
							});
						} else {
							// 如果没有获取到图片，使用默认图片
							imageUrls = ['/static/url/defualt_1.png', '/static/url/defualt_2.png'];
						}
            console.log("******2");

						// 构建跳转参数
						const params = {
							bookName: encodeURIComponent(item.bookName),
							bookId: item.id || '',
							isCollected: false, // 默认未收藏
							images: encodeURIComponent(JSON.stringify(imageUrls))
						};

						// 将参数转换为URL查询字符串
						const queryString = Object.keys(params)
							.filter(key => params[key] !== '')
							.map(key => `${key}=${params[key]}`)
							.join('&');

						console.log('跳转到图片轮播页面:', params);

						// 跳转到图片轮播页面
						uni.navigateTo({
							url: `/pages/video/player?${queryString}`
						});
					} catch (error) {
						console.error('获取书籍详情失败:', error);
						// 如果获取失败，使用默认图片跳转
						const params = {
							bookName: encodeURIComponent(item.bookName),
							bookId: item.id || '',
							isCollected: false,
							images: encodeURIComponent(JSON.stringify(['/static/url/defualt_1.png', '/static/url/defualt_2.png']))
						};

						const queryString = Object.keys(params)
							.filter(key => params[key] !== '')
							.map(key => `${key}=${params[key]}`)
							.join('&');

						uni.navigateTo({
							url: `/pages/video/player?${queryString}`
						});
					}
				} else {
          console.log("******3");

          // 普通书架书籍，跳转到书籍详情页面
					const params = {
						title: item.title,
						id: item.id || '',
						catalogueId: item.catalogueId || '',
						categoryName: item.categoryName || '',
						author: item.author || ''
					};

					// 将参数转换为URL查询字符串
					const queryString = Object.keys(params)
						.filter(key => params[key] !== '')
						.map(key => `${key}=${encodeURIComponent(params[key])}`)
						.join('&');

					uni.navigateTo({
						url: `/pages/book/bookDetail?${queryString}`
					});
				}
			},
			// 加载绘本数据
			async loadBookData(type,id) {
				try {
					// 调用接口获取英文书架绘本数据
          let response;
          if (id === undefined){
             response = await BookShelfApi.getCategoryList({
              type: type
            });
          }else{
            response = await BookShelfApi.getCategoryList({
              type: type,
              id: id
            });
          }
          this.oxfordTree = response.data;
				} catch (error) {
					console.error('获取绘本数据失败:', error);
				}
			},
			// 加载最近阅读记录
			async loadRecentlyRead() {
				try {
					// 调用接口获取阅读记录
					const response = await BookRecordApi.queryMyRecentlyReadBooks('1');

					if (response.code === 0 && response.data ) {


						this.recentlyRead = response.data;
						console.log('最近阅读记录加载成功:', this.recentlyRead);
					} else {
						console.warn('获取阅读记录失败，使用默认数据');
						// 保持原有的默认数据
					}
				} catch (error) {
					console.error('获取阅读记录失败:', error);
					// 保持原有的默认数据
				}
			},

			// 移动到回收站
			async moveToRecycleBin(item) {
        uni.showToast({
          title: '暂未开放',
          icon: 'none'
        });
        return;

				if (!item.id) {
					uni.showToast({
						title: '书籍ID不存在',
						icon: 'none'
					});
					return;
				}

				try {
					// 显示确认对话框
					const confirmResult = await new Promise((resolve) => {
						uni.showModal({
							title: '确认操作',
							content: `确定要将"${item.title}"移入回收站吗？`,
							confirmText: '确定',
							cancelText: '取消',
							success: (res) => {
								resolve(res.confirm);
							},
							fail: () => {
								resolve(false);
							}
						});
					});

					if (!confirmResult) {
						return;
					}

					// 调用回收站接口
					const response = await BookShelfApi.updateBookShelfRecycleBin(item.id, true);

					if (response.code === 200 || response.code === 0) {
						uni.showToast({
							title: '已移入回收站',
							icon: 'success'
						});

						// 刷新数据
						await this.loadBookData();
						await this.loadRecentlyRead();
					} else {
						uni.showToast({
							title: response.msg || '操作失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('移入回收站失败:', error);
					uni.showToast({
						title: '操作失败，请重试',
						icon: 'none'
					});
				}
			}
		}
	};
</script>

<style lang="scss">
	.wrap {
		padding: 10rpx;
		background-color: #fff;
	}

	.status-bar {
		width: 100%;
		background-color: #fff;
	}

	.search-bar {
		display: flex;
		align-items: center;
		padding: 0 30rpx;
		background-color: #fff;
		gap: 20rpx;
	}

	.dir {
		display: flex;
		align-items: center;
		gap: 8rpx;
		flex-shrink: 0;
	}

	.dir-text {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
	}

	.search-container {
		flex: 1;
		margin: 0 20rpx;
	}

	.search-btn {
		width: 70rpx;
		height: 70rpx;
		border-radius: 50%;
		background-color: #ff8c00;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-shrink: 0;
		box-shadow: 0 4rpx 12rpx rgba(255, 140, 0, 0.3);
	}

	.content {
		padding: 20rpx;
	}

	.plan-section {
		padding: 20rpx 0;
	}

	.plan-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.title {
		font-size: 32rpx;
		font-weight: bold;
		color: #007aff;
	}

	.plan-actions {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.view-all {
		color: #000;
		font-size: 26rpx;
	}

	.create-plan {
		color: #000;
		font-size: 28rpx;
	}

	.category-section {
		margin-top: 30rpx;
	}

	.category-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.book-card {
		width: 95%;
		display: flex;
		flex-direction: column;
		margin-bottom: 20rpx;
	}

	.book-cover {
		height: 250rpx;
		border-radius: 12rpx;
		position: relative;
		margin-bottom: 10rpx;
    background-size: contain;
    background-position: center;
    background-repeat: no-repeat;
	}

	.book-count {
		position: absolute;
		top: 10rpx;
		left: 10rpx;
		background-color: rgba(0, 0, 0, 0.3);
		color: white;
		padding: 2rpx 10rpx;
		border-radius: 20rpx;
		font-size: 20rpx;
	}

	.book-title {
		font-size: 26rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.book-meta {
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 22rpx;
		color: #999;
	}

	.recycle-icon {
	position: absolute;
	bottom: 8rpx;
	right: 8rpx;
	width: 32rpx;
	height: 32rpx;
	border-radius: 50%;
	background-color: rgba(255, 255, 255, 0.8);
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
	transition: all 0.3s ease;
	z-index: 10;
}

	.recycle-icon:hover {
		background-color: rgba(255, 0, 0, 0.9);
		transform: scale(1.1);
	}

	.plan-list {
		margin-top: 20rpx;
	}

	.plan-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 24rpx 20rpx;
		margin-bottom: 16rpx;
		background-color: #f8f9fa;
		border-radius: 12rpx;
		border-left: 4rpx solid #007aff;
	}

	.plan-content {
		flex: 1;
	}

	.plan-header-info {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 8rpx;
	}

	.plan-name {
		font-size: 28rpx;
		font-weight: 500;
		color: #333;
		flex: 1;
	}

	.plan-type {
		font-size: 22rpx;
		color: #007aff;
		background-color: rgba(0, 122, 255, 0.1);
		padding: 4rpx 12rpx;
		border-radius: 12rpx;
		flex-shrink: 0;
	}

	.plan-progress {
		display: flex;
		align-items: center;
	}

	.progress-text {
		font-size: 24rpx;
		color: #666;
	}

	.plan-arrow {
		flex-shrink: 0;
	}

	.plan-empty {
		text-align: center;
		padding: 40rpx 20rpx;
	}

	.empty-text {
		font-size: 26rpx;
		color: #999;
	}
</style>
